import { Context } from 'koa';
import crypto from 'crypto';
import uuid from 'node-uuid';
const uidv4 = uuid.v4();
import dtime from 'time-formater';
import AuthModel from '../dbs/models/users';

class AuthController {
  constructor() {
    this.login = this.login.bind(this)
  }

  async login(ctx) {
    const regEmail = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    const { email, password } = ctx.request.body;
    if (!email || !password) {
      ctx.body = {
        code: 40001,
        message: '用户名或密码为空',
        data: null
      }
    } else if (!regEmail.test(email)) {
      ctx.body = {
        code: 40002,
        message: '邮箱格式错误',
        data: null
      }
    } else if (password.length < 6 || password.length > 16) {
      ctx.body = {
        code: 40003,
        message: '密码长度为6-16位字符',
        data: null
      }
    } else {
      // console.log(AuthModel)
      const admin = await AuthModel.Users.findOne({ email })
      if (!admin) {
        const uid = uidv4
        const newPass = this.encryption(password)
        const newAccount = {
          uid,
          email,
          password: newPass,
          create_time: dtime().format('YYYY-MM-DD HH:mm:ss'),
          nickname: `昵称${uid.substr(uid.length - 4, 4)}`,
          status: 1
        }
        await AuthModel.Users.create(newAccount)
        const admin = await AuthModel.Users.findOne({ email })
        if (admin) {
          ctx.body = {
            code: 20000,
            message: '登录成功',
            data: {
              email,
              uid: newAccount.uid
            }
          }
        } else {
          ctx.body = {
            code: 40001,
            message: '登录失败',
            data: null
          }
        }
      }
      const newUser = await AuthModel.Users.findOne({ email })
      ctx.body = {
        code: 20000,
        message: '登录成功',
        data: {
          email,
          uid: newUser.uid,
          nickname: newUser.nickname,
          createTime: newUser.create_time
        }
      }
    }
  }

  encryption(password) {
    const newPassword = this.Md5(this.Md5(password).substr(2, 7) + this.Md5(password));
    return newPassword;
  }
  Md5(pass) {
    const md5 = crypto.createHash('md5');
    return md5.update(pass).digest('base64');
  }
}

export default new AuthController()